import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 6000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    // 错误统一处理

    console.dir(error.response.status)
    if (error?.response?.status === 401) {
      Message.error('登录信息已过期，请重新登录')
      // 1. 跳转到登录
      store.dispatch('user/handlelogout')
      router.push('/login')
    }
    Message.error(error?.response?.data?.message || '网络错误')
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

export default service
